<template>
    <el-container>
        <el-header>
            <el-row>
                <el-col :span="12"><i class="el-icon-arrow-left" @click="$router.back(-1)"></i></el-col>
                <el-col :span="8"><span class="name-title">{{ground.name}}</span></el-col>
                <el-col :span="4">
                    <i class="el-icon-edit" @click="handleEdit"></i>
                    <i class="el-icon-delete" @click="handleDelete"></i>
                </el-col>
            </el-row>
        </el-header>
        <el-container>
            <el-aside width="300px" class="user-header-bg">
                <img :src="ground.imgKey" v-if="ground.imgKey!=''&&ground.imgKey!=null"
                     style="width: 150px;height: 150px">
                <img src="@/assets/orchard.jpg" v-else
                     style="width: 180px;height: 150px">
            </el-aside>
            <el-main class="user-info-bg">
                <el-row>
                    <el-col :span="8">编号：{{ground.groundCode}}</el-col>
                    <el-col :span="8">果园名称：{{ground.name}}</el-col>
                    <el-col :span="8">农户名称：{{ground.farmerName}}</el-col>
                </el-row>
                <el-row class="user-row">
                    <el-col :span="8">面积：{{ground.acreage}}亩</el-col>
                    <el-col :span="8">附属地面积：{{ground.attachedArea}}亩</el-col>
                    <el-col :span="8">授粉树品种：{{ground.pollinationTreeType?ground.pollinationTreeType.name:'暂无'}}</el-col>
                </el-row>
                <el-row class="user-row">
                    <el-col :span="8">是否有防冰雹网：{{ground.protectHailNet?"是":"否"}}</el-col>
                    <el-col :span="8">是否是基本农田：{{ground.farmlandFlag?'是':'否'}}</el-col>
                    <el-col :span="8">地块从属：{{ground.attributionType?ground.attributionType.name:'暂无'}}</el-col>
                </el-row>
                <el-row class="user-row">
                    <el-col :span="8">用途：{{ground.purpose?ground.purpose:'暂无'}}</el-col>
                    <el-col :span="8">详细地址：{{ground.address?ground.address:'暂无'}}</el-col>
                </el-row>
            </el-main>
        </el-container>
        <!--果树列表-->
        <el-container>
            <!--<el-header class="header-bg">-->
            <!--<span class="header-title">果树列表</span>-->
            <!--</el-header>-->
            <div class="ground-bg">
                <el-tabs v-model="tabIndex" type="border-card" stretch @tab-click="handleTab">
                    <el-tab-pane label="果树列表">
                        <el-row>
                            <el-col
                                    :span="6"
                                    :offset="20"
                            >
                                <el-button
                                        type="primary"
                                        icon="el-icon-fa-plus"
                                        size="small"
                                        @click="treeShow=true"
                                >
                                    添加果树
                                </el-button>
                            </el-col>
                        </el-row>
                        <el-table
                                :data="dataList"
                                border
                                stripe
                                style="width: 100%"
                        >
                            <el-table-column
                                    prop="id"
                                    label="ID"
                            />
                            <el-table-column
                                    prop="treeType.name"
                                    label="果树类型"
                            />
                            <el-table-column
                                    prop="treeAge"
                                    label="树龄"
                            />
                            <el-table-column
                                    prop="amount"
                                    label="数量"
                            />
                            <el-table-column label="操作">
                                <template slot-scope="scope">
                                    <el-button-group>
                                        <el-button
                                                title="编辑"
                                                size="mini"
                                                type="primary"
                                                icon="el-icon-fa-edit"
                                                @click="treeEdit(scope.row)"
                                        >
                                            编辑
                                        </el-button>
                                        <el-button
                                                title="删除"
                                                size="mini"
                                                type="primary"
                                                icon="el-icon-fa-trash"
                                                @click="treeDelete(scope.row)"
                                        >
                                            删除
                                        </el-button>
                                    </el-button-group>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-tab-pane>
                    <el-tab-pane label="产量">
                        <el-row>
                            <el-col :span="4">
                                <el-select
                                        v-model="year"
                                        @change="doSearch"
                                        placeholder="请选择年份">
                                    <div slot="prefix" style="line-height: 32px;color:#909399;">年份</div>
                                    <el-option
                                            v-for="(item,index) in years"
                                            :key="index"
                                            :label="item"
                                            :value="item"/>
                                </el-select>
                            </el-col>
                            <el-col
                                    :span="6"
                                    :offset="14"
                            >
                                <el-button
                                        type="primary"
                                        icon="el-icon-fa-plus"
                                        size="small" v-if="addFlag===1"
                                        @click="goYield"
                                >
                                    添加产量
                                </el-button>
                            </el-col>
                        </el-row>
                        <el-card class="box-card">
                            <div slot="header" class="clearfix">
                                <span style="font-weight: bold">{{year}}年产量</span>
                                <el-button style="float: right; padding: 3px 0 0 10px" v-if="!!yields.baged" type="text"
                                           @click.native="goDel">删除
                                </el-button>
                                <el-button style="float: right; padding: 3px 0" type="text" v-if="!!yields.baged"
                                           @click.native="goEdit">编辑
                                </el-button>
                            </div>
                            <el-container style="font-size: 14px">
                                <el-main>
                                    <el-row>
                                        <el-col :span="6">套袋数：{{yields.baged?yields.baged.amount:0}}个</el-col>
                                        <el-col :span="6">商品果：{{yields.commodity?yields.commodity.amount:0}}斤
                                            <div class="bottom clearfix">
                                                <time class="time">价格：{{yields.commodity?yields.commodity.price:0}}元/斤
                                                </time>
                                            </div>
                                        </el-col>
                                        <el-col :span="6">次果：{{yields.defective?yields.defective.amount:0}}斤
                                            <div class="bottom clearfix">
                                                <time class="time">价格：{{yields.defective?yields.defective.price:0}}元/斤
                                                </time>
                                            </div>
                                        </el-col>
                                        <el-col :span="6">果汁果：{{yields.juice?yields.juice.amount:0}}斤
                                            <div class="bottom clearfix">
                                                <time class="time">价格：{{yields.juice?yields.juice.price:0}}元/斤</time>
                                            </div>
                                        </el-col>
                                    </el-row>
                                </el-main>
                            </el-container>
                        </el-card>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </el-container>
        <el-dialog
                :title="tree.id===0?'添加果树':'编辑果树'"
                :visible.sync="treeShow"
                append-to-body
                width="30%"
        >
            <el-form
                    :model="tree"
                    :rules="treeRules"
                    ref="treeForm"
            >
                <el-form-item
                        label="果树类型"
                        :label-width="labelWidth"
                        prop="treeType"
                >
                    <el-select
                            v-model="tree.treeType"
                            placeholder="请选择果树类型"
                    >
                        <el-option
                                v-for="item in treeTypes"
                                :key="item.value"
                                :label="item.name"
                                :value="item.value"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item
                        label="树龄"
                        :label-width="labelWidth"
                        prop="treeAge"
                >
                    <el-input
                            v-model="tree.treeAge"
                            auto-complete="off"
                            maxlength="11"
                            suffix-icon="fa fa-mobile"
                            placeholder="请填写树龄"
                    />
                </el-form-item>
                <el-form-item
                        label="数量"
                        :label-width="labelWidth"
                        prop="amount"
                >
                    <el-input
                            v-model="tree.amount"
                            auto-complete="off"
                            maxlength="12"
                            suffix-icon="fa fa-mobile"
                            placeholder="请填写果树数量"
                    />
                </el-form-item>
            </el-form>
            <div style="text-align: center;margin-top: 20px">
                <el-button
                        size="small"
                        @click="cancelTree('treeForm')"
                >
                    取 消
                </el-button>
                <el-button
                        size="small"
                        type="primary"
                        @click="submitTree('treeForm')"
                >
                    确 定
                </el-button>
            </div>
        </el-dialog>
        <!--产量-->
        <el-dialog
                :title="income.id===0?'添加产量':'编辑产量'"
                :visible.sync="yieldShow"
                append-to-body
                width="30%"
        >
            <el-form
                    :model="income"
                    ref="yieldForm"
            >
                <el-form-item
                        label="年份"
                        :label-width="labelWidth"
                        prop="year"
                >
                    <span>{{income.year}}</span>
                </el-form-item>
                <el-form-item
                        label="套袋数"
                        :label-width="labelWidth"
                        :rules="[{required: true, validator: $validator.numValid, trigger: 'blur'}]"
                        prop="bag.amount"
                >
                    <el-input
                            v-model="income.bag.amount"
                            auto-complete="off"
                            maxlength="11"
                            suffix-icon="fa fa-shopping-basket"
                            placeholder="请填写套袋数">
                        <template slot="append">个</template>
                    </el-input>
                </el-form-item>
                <div v-for="(item, i) in income.incomes" :key="i">
                    <el-form-item
                            :label="item.fruitName+'产量'"
                            :label-width="labelWidth"
                            :rules="item.amountRule"
                            :prop="'incomes.'+i+'.amount'"
                    >
                        <el-input
                                v-model="item.amount"
                                auto-complete="off"
                                maxlength="12"
                                suffix-icon="fa fa-balance-scale"
                                placeholder="请填写产量"
                        >
                            <template slot="append">斤</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item
                            :label="item.fruitName+'单价'"
                            :label-width="labelWidth"
                            :rules="item.unitPriceRule"
                            :prop="'incomes.'+i+'.unitPrice'">
                        <el-input
                                v-model="item.unitPrice"
                                auto-complete="off"
                                maxlength="12"
                                suffix-icon="fa fa-th"
                                placeholder="请填写单价"
                        >
                            <template slot="append">元/斤</template>
                        </el-input>
                    </el-form-item>
                </div>
            </el-form>
            <div style="text-align: center;margin-top: 20px">
                <el-button
                        size="small"
                        @click="cancelYield('yieldForm')"
                >
                    取 消
                </el-button>
                <el-button
                        size="small"
                        type="primary"
                        @click="submitYield('yieldForm')"
                >
                    确 定
                </el-button>
            </div>
        </el-dialog>
        <AddAndEdit
                v-model="addAndEditValue"
                @on-show-change="addAndEditDone"
        />
    </el-container>
</template>
<script>
    import AddAndEdit from "./AddAndEdit";
    import {mapState} from "vuex";

    export default {
        components: {
            AddAndEdit: AddAndEdit
        },
        data() {
            return {
                addFlag: 0,
                years: [],
                year: '',
                tabIndex: 0,
                yields: {},
                fruitLevels: [],
                income: {id: 0, year: null, bagRule: [], bag: {amount: ''}, incomes: []},
                dataList: [],
                id: 0,
                treeShow: false,
                yieldShow: false,
                labelWidth: '',
                ground: {},
                addAndEditValue: {
                    show: false,
                    ground: {id: 0}
                },
                tree: {
                    id: 0,
                    groundId: '',
                    treeType: '',
                    treeAge: '',
                    amount: ''
                },
                treeTypes: [],
                treeRules: {
                    treeType: [{required: true, message: "请选择果树类型", trigger: "blur"}],
                    treeAge: [{required: true, validator: this.$validator.decimalValid, trigger: "blur"}],
                    amount: [{required: true, validator: this.$validator.numValid, trigger: "blur"}],
                }
            }
        },
        computed: {
            ...mapState({
                codebooks: state => state.codebooks.codebooks
            })
        },
        mounted() {
            this.id = Number(this.$route.query.id);
            this.treeTypes = this.codebooks ? this.codebooks.treeTypes : [];
            this.fruitLevels = this.codebooks ? this.codebooks.fruitLevels : [];
            this.loadGround(this.id);
            this.loadTree(this.id);
            this.initYears();
            this.loadYield();
        },
        methods: {
            initYears() {
                //设置年份的选择
                var myDate = new Date();
                var startYear = myDate.getFullYear() - 10;//起始年份
                var endYear = myDate.getFullYear();//结束年份
                this.year = endYear;
                for (var i = startYear; i <= endYear; i++) {
                    this.years.push(i);
                }
                this.years.reverse();
            },
            goYield() {
                this.loadIncome();
                this.income.year = this.year;
                this.yieldShow = true;
            },
            goEdit() {
                this.income.year = this.year;
                this.goYield();
            },
            goDel() {
                this.$confirm("此操作将删除该年果园的产量, 是否继续?", "删除提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                    this.$api.ground.deleteYield(this.id, this.yields.year, () => {
                        this.$message({
                            type: "success",
                            message: "删除产量成功"
                        });
                        this.loadYield();
                    });
                });
            },
            loadYield() {
                this.$api.ground.yields(this.id, this.year, result => {
                    this.yields = result.yields && result.yields.length > 0 ? result.yields[0] : {};
                    if (this.yields.year) {
                        this.addFlag = 0;
                    } else {
                        this.addFlag = 1;
                    }
                })
            },
            loadIncome() {
                this.$api.ground.yieldDetail(this.id, this.income.year ? this.income.year : 0, result => {
                    if (result.bagAmount) {
                        this.income.id = result.bagAmount.id;
                        this.income.bag.id = result.bagAmount.id;
                        this.income.bag.amount = result.bagAmount.amount;
                    }
                    this.income.bag.groundId = this.id;
                    this.income.bag.farmerId = this.ground.farmerId;
                    this.income.bag.year = this.income.year;
                    this.income.incomes = this.fruitLevels.map(item => {
                        let income = this.checkExist(item, result.incomes);
                        let obj;
                        if (income && income.id) {
                            obj = {
                                id: income.id,
                                groundId: income.groundId,
                                fruitLevel: item.value,
                                fruitName: item.name,
                                amount: income.amount,
                                unitPrice: income.unitPrice,
                                sumPrice: income.sumPrice,
                                farmerId: income.farmerId,
                                amountRule: [{required: true, message: `请输入${item.name}的数量`, trigger: "blur"},
                                    {
                                        pattern: this.$validator.decimalValid,
                                        message: `请输入正确的${item.name}数量`,
                                        trigger: 'blur'
                                    }],
                                unitPriceRule: [{required: true, message: `请输入${item.name}的单价`, trigger: "blur"},
                                    {
                                        pattern: this.$validator.decimalValid,
                                        message: `请输入正确的${item.name}单价`,
                                        trigger: 'blur'
                                    }],
                            };
                        } else {
                            obj = {
                                id: 0,
                                groundId: this.id,
                                farmerId: this.ground.farmerId,
                                fruitLevel: item.value,
                                fruitName: item.name,
                                amount: "",
                                unitPrice: "",
                                sumPrice: "",
                                year: this.income.year,
                                amountRule: [{required: true, message: `请输入${item.name}的数量`, trigger: "blur"},
                                    {
                                        pattern: /^([1-9]\d*|0)(\.\d{1,2})?$/,
                                        message: `请输入正确的${item.name}数量`,
                                        trigger: 'blur'
                                    }],
                                unitPriceRule: [{required: true, message: `请输入${item.name}的单价`, trigger: "blur"},
                                    {
                                        pattern: /^([1-9]\d*|0)(\.\d{1,2})?$/,
                                        message: `请输入正确的${item.name}单价`,
                                        trigger: 'blur'
                                    }],
                            };
                        }
                        return obj;
                    });
                });
            },
            checkExist(fruitItem, incomes) {
                let obj = {};
                for (let i in incomes) {
                    if (incomes[i].fruitLevel.value === fruitItem.value) {
                        obj = incomes[i];
                        break;
                    }
                }
                return obj;
            },
            loadGround(id) {
                this.$api.ground.detail(id, result => {
                    this.ground = result.ground;
                    if (this.ground && this.ground.imgKey) {
                        this.ground.imgKey = this.$config.app.ossPrefix + this.ground.imgKey;
                    }
                })
            },
            cancelYield(formName) {
                this.$refs[formName].clearValidate();
                this.income = {id: 0, year: null, bag: {amount: ''}, incomes: []};
                this.yieldShow = false;
                this.loadYield();
            },
            submitYield(formName) {
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        const callback = () => {
                            this.cancelYield(formName);
                        };
                        let param = {
                            yield: this.income.bag,
                            incomes: this.income.incomes
                        };
                        this.$api.ground.setYield(param, callback);
                    } else {
                        return false;
                    }
                });
            },
            addAndEditDone(data) {
                this.addAndEditValue.show = data.visible;
                this.loadGround(this.id);
            },
            handleEdit() {
                this.addAndEditValue = {show: true, ground: this.ground};
            },
            handleDelete() {
                this.$confirm("此操作将删除该土地, 是否继续?", "删除提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                    this.$api.tree.delete(this.id, () => {
                        this.$message({
                            type: "success",
                            message: "删除土地成功"
                        });
                        this.$router.push({path: "/ground"})
                    });
                });
            },
            loadTree(groundId) {
                this.$api.ground.getTrees(groundId, result => {
                    this.dataList = result.trees;
                });
            },
            submitTree(formName) {
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        const callback = () => {
                            this.cancelTree(formName);
                        };
                        this.tree.id > 0
                            ? this.$api.tree.update(this.tree, callback)
                            : this.$api.tree.save(this.tree, callback);
                    } else {
                        return false;
                    }
                });
            },
            cancelTree(formName) {
                this.treeShow = false;
                this.tree = {
                    id: 0,
                    groundId: this.ground.id
                }
                this.$refs[formName].clearValidate();
                //加载列表数据
                this.loadTree(this.id);
            },
            treeEdit(row) {
                //查询
                this.$api.tree.detail(row.id, result => {
                    this.tree = result.tree;
                    this.tree.treeType = this.tree.treeType ? this.tree.treeType.value : '';
                    this.$delete(this.tree, "status");
                    this.treeShow = true;
                })
            },
            treeDelete(row) {
                this.$confirm("此操作将删除该果树, 是否继续?", "删除提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                    this.$api.tree.delete(row.id, () => {
                        this.$message({
                            type: "success",
                            message: "删除果树成功",
                            onClose: () => {
                                this.loadTree(this.id);
                            }
                        });
                    });
                });
            },
            doSearch() {
                this.loadYield();
            },
            handleTab() {
                if (this.tabIndex == 1) {
                    this.year = new Date().getFullYear();
                    this.doSearch();
                } else {
                    this.loadTree(this.id);
                }
            }
        }
    }
</script>
<style scoped>
    .user-row {
        margin-top: 10px
    }

    .ground-bg {
        width: 100%;
        margin-top: 10px;
    }

    .el-icon-edit {
        margin-left: 50px;
        font-size: 20px;
        color: dodgerblue;
        cursor: pointer;
    }

    .name-title {
        font-size: 20px;
        font-weight: bold
    }

    .el-icon-delete {
        font-size: 20px;
        color: red;
        margin-left: 30px;
        cursor: pointer;
    }

    .user-header-bg {
        margin-top: 15px;
        margin-left: 5%
    }

    .user-info-bg {
        font-size: 14px;
        color: #545c64
    }

    .header-bg {
        height: 40px !important;
        margin-top: 50px;
        background-color: #409EFF
    }

    .header-title {
        line-height: 40px;
        color: white
    }

    .box-card {
        margin-top: 20px;
    }
</style>